package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.hustcad.plm.caddocapi.service.TyplmCADDocumentService;
import com.hustcad.plm.pdm.doc.service.TyplmDocQueryService;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.lifestage.model.dto.EntityLifeCycleDTO;
import com.hustcad.plm.pdm.lifestage.service.TyplmLifecycleTemplateService;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.cad.CADDocDO;
import com.ty.basic.entity.doc.DocDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.service.ExpiredOldVersionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;


/**
 * @author fxw
 * @version 1.0
 * @className ExpiredOldVersionsServiceImpl
 * @description 失效过期的历史版本
 * @since 2025/11/19 10:30
 */
@Service
@Slf4j
public class ExpiredOldVersionsServiceImpl implements ExpiredOldVersionsService {
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private TyplmCADDocumentService typlmCADDocumentService;
    @Resource
    private TyplmDocQueryService typlmDocQueryService;
    @Resource
    private TyplmLifecycleTemplateService typlmLifecycleTemplateService;
    @Resource
    private TyplmUserService typlmUserService;

    @Override
    public void performAnInvalidHistoricalVersion(BigInteger workFlowContainerId) {
        UserDO user = this.typlmUserService.queryUserByName("admin");
        if (Objects.nonNull(user)) {
            TyAccountContext.setUser(user);
        }
        // 根据工作流容器ID获取容器视图详情
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                workFlowContainerId);
        // 检查容器是否为WorkFlowObjectPackage类型且不为空
        if (workFlowContainerView instanceof WorkFlowObjectPackage) {
            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
            List<FlowObject> flowObjectList = workFlowObjectPackage.getFlowObjectList();

            if (CollUtil.isEmpty(flowObjectList)) {
                return;
            }
            //获取流程的对象
            List<FlowObject> cadFlowList = new ArrayList<>();
            List<FlowObject> docFlowList = new ArrayList<>();
            Map<String, FlowObject> map = new HashMap<>();
            for (FlowObject flowObject : flowObjectList) {
                String refObjectOtype = flowObject.getRefObjectOtype();
                if (TableTypeConstrant.TY_CADDOC_OTYPE.equals(refObjectOtype)) {
                    map.put(flowObject.getRefObjectOid().toString(), flowObject);
                    cadFlowList.add(flowObject);
                } else if (TableTypeConstrant.TY_DOC_OTYPE.equals(refObjectOtype)) {
                    map.put(flowObject.getRefObjectOid().toString(), flowObject);
                    docFlowList.add(flowObject);
                }
            }
            //针对图纸的历史版本失效
            List<EntityLifeCycleDTO> objects = new ArrayList<>();
            if (CollUtil.isNotEmpty(cadFlowList)) {
                cadFlowList.forEach(flowObject -> {
                    CADDocDO cadDocDO = typlmCADDocumentService.queryCADDocByOID(flowObject.getRefObjectOid());
                    BigInteger versionsort = Convert.toBigInteger(cadDocDO.getVersionsort());
                    List<CADDocDO> cadDocDOS = typlmCADDocumentService.queryCADDocHistory(flowObject.getRefObjectOid(),
                                                                                          TableTypeConstrant.TY_CADDOC_OTYPE);
                    if (cadDocDOS.size() > 1) {
                        cadDocDOS.stream().filter(
                                        history -> versionsort.compareTo(Convert.toBigInteger(history.getVersionsort())) > 0)
                                .forEach(docDo -> {
                                    objects.add(invalidObject(docDo));
                                });
                    }
                });

            }
            //针对文档的历史版本失效
            if (CollUtil.isNotEmpty(docFlowList)) {
                docFlowList.forEach(flowObject -> {
                    DocDO docDO = typlmDocQueryService.queryDocByOID(flowObject.getRefObjectOid());
                    BigInteger versionsort = Convert.toBigInteger(docDO.getVersionsort());
                    List<DocDO> docDOS = typlmDocQueryService.queryDocHistory(flowObject.getRefObjectOid(),
                                                                              TableTypeConstrant.TY_DOC_OTYPE);
                    if (docDOS.size() > 1) {
                        docDOS.stream().filter(
                                        history -> versionsort.compareTo(Convert.toBigInteger(history.getVersionsort())) > 0)
                                .forEach(docDo -> {
                                    objects.add(invalidObject(docDo));
                                });
                    }
                });

            }
            if (CollUtil.isNotEmpty(objects)) {
                //更新状态
                typlmLifecycleTemplateService.batchUpdateEntityLifecycle(objects, true, false, false);
            }
        }
    }

    //更新对象
    private EntityLifeCycleDTO invalidObject(DocDO docDo) {
        EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
        entityLifeCycleDTO.setOid(docDo.getOid());
        entityLifeCycleDTO.setOtype(docDo.getOtype());
        entityLifeCycleDTO.setLifeCycleStageKey("DISABLED");
        return entityLifeCycleDTO;
    }
    private EntityLifeCycleDTO invalidObject(CADDocDO cadDocDO) {
        EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
        entityLifeCycleDTO.setOid(cadDocDO.getOid());
        entityLifeCycleDTO.setOtype(cadDocDO.getOtype());
        entityLifeCycleDTO.setLifeCycleStageKey("DISABLED");
        return entityLifeCycleDTO;
    }


}